<!-- 工单管理 -->
<template>
	<div class="work-order" v-loading="state.loading">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form :model="state.queryParams" ref="queryForm" :inline="true">
				<el-form-item label="开始时间">
					<el-date-picker v-model="state.queryParams.startTime" type="datetime" placeholder="开始时间" value-format="YYYY-MM-DD HH:mm:ss" :shortcuts="shortcuts" />
				</el-form-item>
				<el-form-item label="结束时间">
					<el-date-picker v-model="state.queryParams.endTime" type="datetime" placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" :shortcuts="shortcuts" />
				</el-form-item>
				<el-form-item label="工单状态">
					<el-select v-model="state.queryParams.ticketstatus" clearable>
						<el-option v-for="(item, index) in state.orderState"
							:key="index"
							:label="item.label"
							:value="item.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Search" @click="handleQuery"> 查询 </el-button>
						<el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
					</el-button-group>
				</el-form-item>
				<!-- <el-form-item>
					<el-button icon="ele-DeleteFilled" type="danger" @click="clearLog" v-auth="'sysOplog:clear'"> 清空 </el-button>
					<el-button icon="ele-FolderOpened" @click="exportLog" v-auth="'sysOplog:export'"> 导出 </el-button>
				</el-form-item> -->
				<el-form-item>
					<el-button type="primary" icon="ele-Plus" @click="openAddMenu()"> 新增 </el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<el-card class="full-table" shadow="hover" style="margin-top: 8px">
			<el-table :data="state.logData" @sort-change="sortChange" style="width: 100%" border>
				<el-table-column type="index" label="序号" width="55" align="center" />
				<el-table-column prop="ticketId" label="工单号" align="center" show-overflow-tooltip />
				<el-table-column prop="regionId" label="区域" align="center" show-overflow-tooltip>
					<template #default="scope">
						{{getLabelByValue(state.orderArea, scope.row.regionId)}}
					</template>
				</el-table-column>
				<el-table-column prop="title" label="故障简述" align="center" show-overflow-tooltip />
				<el-table-column prop="applyName" label="申报人" align="center" show-overflow-tooltip />
				<el-table-column prop="cellPhone" label="电话" align="center" show-overflow-tooltip />
				<el-table-column prop="address" label="地址" align="center" show-overflow-tooltip />
				<el-table-column prop="operatorName" label="创建人" align="center" show-overflow-tooltip />
				<el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip />
				<el-table-column prop="engineerName" label="服务工程师" align="center" show-overflow-tooltip />
				<el-table-column prop="status" label="状态" width="70" align="center" show-overflow-tooltip>
					<template #default="scope">
						{{getLabelByValue(state.orderState, scope.row.status)}}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="150" align="center" fixed="right" show-overflow-tooltip>
					<template #default="scope">
						<el-button v-if="scope.row.status >= 4" icon="el-icon-edit" size="small" text type="primary" @click="viewDetail(scope.row)">查看</el-button>
						<el-button v-else icon="el-icon-edit" size="small" text type="primary" @click="openAddMenu(scope.row)">编辑</el-button>
						<el-button v-if="scope.row.status < 5" icon="el-icon-edit" size="small" text type="primary" @click="handleDelete(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-model:currentPage="state.tableParams.page"
				v-model:page-size="state.tableParams.pageSize"
				:total="state.tableParams.total"
				:page-sizes="[10, 20, 50, 100]"
				small
				background
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper"
			/>
		</el-card>

		<AddModal ref="AddModalRef" @reload="handleQuery"></AddModal>
		<DetailModal ref="DetailModalRef" @reload="handleQuery"></DetailModal>
	</div>
</template>

<script lang="ts" setup name="workOrder">
import { onMounted, reactive, ref } from 'vue';
import {useRouter, useRoute} from "vue-router";
import { ElMessage, ElMessageBox } from 'element-plus';
import {Session} from "/@/utils/storage.ts";
import { downloadByData, getFileName } from '/@/utils/download';
import AddModal from "./modules/AddModal.vue";
import DetailModal from "./modules/DetailModal.vue";
import {getLabelByValue} from "/@/utils/Tools.js";
import { getAPI } from '/@/utils/axios-utils';
import { SysDictDataApi } from '/@/api-services/api';
import { getOrderList, orderDelete } from '/@/api/order/index.js';

const router = useRouter();
const route = useRoute();
const AddModalRef = ref();
const DetailModalRef = ref();

const state = reactive({
	loading: false,
	queryParams: {
		startTime: undefined,
		endTime: undefined,
		ticketstatus: ''
	},
	tableParams: {
		page: 1,
		pageSize: 20,
		field: 'createTime', // 默认的排序字段
		order: 'descending', // 排序方向
		descStr: 'descending', // 降序排序的关键字符
		total: 0 as any,
	},
	// logData: [] as Array<SysLogOp>,
	logData: [],
	dialogVisible: false,
	content: '',

	// 区域
	orderArea: [],
	// 故障类型
	faultType: [],
	// 工单状态
	orderState: []
});

onMounted(async () => {
	

	$Dict.get('order_area').then(res => {
		state.orderArea = res;
	})
	$Dict.get('fault_type').then(res => {
		state.faultType = res;
	})
	$Dict.get('order_state').then(res => {
		console.log(res);
		state.orderState = res;
	})

	handleQuery();

	setTimeout(() => {
		// id -1添加，xxx编辑
		let id = Session.get('workOrderShowId');
		if(id == -1) {
			openAddMenu();
			Session.remove('workOrderShowId');
		}
	}, 200);
});

// 查询操作
const handleQuery = async () => {
	if (state.queryParams.startTime == null) state.queryParams.startTime = undefined;
	if (state.queryParams.endTime == null) state.queryParams.endTime = undefined;

	state.loading = true;
	let params = Object.assign(state.queryParams, state.tableParams);
	params = JSON.parse(JSON.stringify(params))
	params.ticketstatus = params.ticketstatus || '0';
	var res = await getOrderList(params);
	state.logData = res.data.result?.items || [];
	state.tableParams.total = res.data.result?.total;
	state.loading = false;
};

// 重置操作
const resetQuery = () => {
	state.queryParams.startTime = undefined;
	state.queryParams.endTime = undefined;
	handleQuery();
};

// 清空日志
const clearLog = async () => {
	state.loading = true;
	await getAPI(SysLogOpApi).apiSysLogOpClearPost();
	state.loading = false;

	ElMessage.success('清空成功');
	handleQuery();
};

// 导出日志
const exportLog = async () => {
	// state.loading = true;
	// var res = await getAPI(SysLogOpApi).apiSysLogOpExportPost(state.queryParams, { responseType: 'blob' });
	// state.loading = false;

	// var fileName = getFileName(res.headers);
	// downloadByData(res.data as any, fileName);
};

// 改变页面容量
const handleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
	state.tableParams.page = val;
	handleQuery();
};

// 查看添加
const openAddMenu = (row:any) => {
	AddModalRef.value.open(row);
}

// 查看详情
const viewDetail = (row: any) => {
	DetailModalRef.value.open(row);
};

// 删除
const handleDelete = (row: any) => {
 	ElMessageBox.confirm('此操作将删除该工单, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
  	let params = {
  		id: row.id
  	}
  	orderDelete(params).then(res => {
			if(res.data.code == 200) {
				ElMessage({
		      type: 'success',
		      message: '删除成功!'
		    });
		    handleQuery();
			}
		})
  }).catch(() => { });
}

// 列排序
const sortChange = (column: any) => {
	state.tableParams.field = column.prop;
	state.tableParams.order = column.order;
	handleQuery();
};
</script>

<style lang="scss" scoped>
.el-popper {
	max-width: 60%;
}
pre {
	white-space: break-spaces;
	line-height: 20px;
}
.el-table .warning-row {
	--el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
	--el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
